package svc

import (
	"fmt"
	"github.com/zeromicro/go-zero/rest"
	"go.zero.learn/internal/config"
	"go.zero.learn/internal/entity/user"
	"go.zero.learn/internal/middleware"
	model "go.zero.learn/model/mongodb"
	"gorm.io/driver/sqlserver"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config              config.Config
	UserAgentMiddleware rest.Middleware
	GormDb              *gorm.DB
	MongoDb             model.TestmongodbModel
}

func NewServiceContext(c config.Config) *ServiceContext {
	// 数据库连接
	gormDb := dbContext(c)
	//迁移数据表
	gormDb.AutoMigrate(&user.UserEntity{})

	mongoDb := mongoDbContext(c)

	return &ServiceContext{
		Config:              c,
		UserAgentMiddleware: middleware.NewUserAgentMiddleware().Handle,
		GormDb:              gormDb,
		MongoDb:             mongoDb,
	}
}

func dbContext(c config.Config) *gorm.DB {
	gormDb, err := gorm.Open(sqlserver.Open(c.Sqlserver), &gorm.Config{})

	if err != nil {
		errInfo := fmt.Sprintf("gorm connect database err: %v", err)
		panic(errInfo)
	}
	return gormDb
}

func mongoDbContext(c config.Config) model.TestmongodbModel {
	return model.NewTestmongodbModel(c.MongoDB.Url, c.MongoDB.DbName, c.MongoDB.Collection)
}
